import { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { View,Text,ScrollView } from '@tarojs/components'
import { connect } from 'react-redux'
import { getAreaInfo } from '@/api/platform'
import { hasPrevRoute } from '@/utils/global'
import { updateCity  } from '@/store/location/action'
import { getDefaultAreaInfo } from '@/api'
import { getAnnualPlatformSaleCity ,getTopicAnnualPlatformSaleCity} from '@/api/order'
import './index.scss'


interface State {
  city:any,
	scrollIntoView:string,
}

@connect<any>(({ location, user }) => ({ location, user }), _dispatch => ({
  dispatchCity(params) {
    return _dispatch(updateCity(params))
  },
}))
class PlatFormCity extends Component<any> {
    $instance = getCurrentInstance();
    constructor (props) {
      super(props)
      this.state = {
				city:[],
				scrollIntoView:''
      }
    }
    state: State
    componentDidMount() {
			let {method='',annualCardId='',isTopicAnnualCard=0} =  this.$instance.router.params
			// getAnnualPlatformSaleCity
			if(method && method == 'annual'){
				let interfaceType = getAnnualPlatformSaleCity
				let params = {
					annualCardId
				}
				// 专题过来的单独处理
				if(isTopicAnnualCard ==1) {
					interfaceType = getTopicAnnualPlatformSaleCity
					params.isTopicAnnualCard = 1
				}

				interfaceType(params).then(resp=>{
					let {data} = resp?.data
					data.list = []
					data.map(item=>{
						item.title = item.firstLetter
						item.key = item.firstLetter
					})
					console.log('data',data)
					let newData = {
						list:data,
						name:'',
					}
					this.setState({
						city:newData
					})
				})
			}else{
				let locationData = Taro.getStorageSync('CURRENT_LONGITUDE_LATITUDE')
				let location = ''
				if(locationData && locationData.latitude){
					location = `${locationData.longitude},${locationData.latitude}`
				}
				getAreaInfo({
					location
				}).then(res=>{
					let {data} = res?.data
					data.list.map(item=>{
						item.title = item.firstLetter
						item.key = item.firstLetter
					})
					this.setState({
						city:data
					})
				})
			}
    }

		componentDidShow(){

		}

		/**
		* 开启定位授权
		**/
		openLocation=()=>{
			Taro.openSetting({
				success (res) {
					console.log(res.authSetting)
				}
			})
		}

		/**
			* 修改城市
		**/
		changeCity= async (e)=> {
			let { type =0 } = this.$instance.router.params
			console.log('this.$instance.router.params',this.$instance.router.params)
			let { dispatchCity } = this.props
			let current = {
				adCode:e.adCode,
				name:e.name,
				districtCode:'',
				latitude:'',
				longitude:''
			}
			await getDefaultAreaInfo({
				adCode:e.adCode
			}).then((resp)=>{
				let {areaCode} = resp?.data.data
				current.districtCode = areaCode
				// dispatchCity(current)
				if(type == 0){
					console.log('执行吗-----000')
					const { dispatchCity } = this.props
					console.log('current',current)
					dispatchCity(current)
					this.setState({
						e
					}, () => {
						Taro.showToast({
							title: '切换城市成功',
							icon: 'none',
							duration: 1800,
							complete: () => {
								if (hasPrevRoute()) {
									const Pages = Taro.getCurrentPages()
									if (Pages[Pages.length - 2].route == 'pages/tabbar/store/index') {
										Taro.switchTab({ url: '/pages/tabbar/index/index' })
									} else {
										Taro.navigateBack({
											delta: 2
										})
									}
								} else {
									Taro.switchTab({ url: '/pages/tabbar/index/index' })
								}
							}
						})
					})
				}else if(type == 1){ // 仅仅只是拿取区域数据而已，不切换小程序区域数据
					let pages = Taro.getCurrentPages(); // 获取当前的页面栈
					let prevPage = pages[pages.length-2]; // 获取上一页面
					prevPage.setData({ //设置上一个页面的值
						selectArea: current
					})
					Taro.navigateBack({
						delta: 1
					})
				}

			}).catch(err=>{
				console.log(err)
			})



		}

    UNSAFE_componentWillReceiveProps() {
    }
    private car: ICar | {} = {}

		handleLetter=(item)=>{
			console.log('item',item)
			this.setState({
				scrollIntoView:item
			})
		}

    onShareAppMessage() {

    }
		// 点击事件
		itemClick=()=>{}
    render() {
			const { city,scrollIntoView } = this.state
			console.log('city',city)
			let {method = ''} = this.$instance.router.params
			const {location} = this.props
			let {isOpenLocation}= location
			console.log('scrollIntoView',scrollIntoView)
      return (
        <View style='height:100vh'>
					<ScrollView
							scrollY={true}
							scrollIntoView={scrollIntoView}
							className='index-list'>
								<View>
									<View className="platform-top">
										{
											city.name && <Text>当前城市：{city.name}</Text>
										}
										{
											!isOpenLocation ? <Text className="platform-blue" onClick={this.openLocation}>开启定位授权</Text> : null
										}
										</View>
										{
											method ? <View className="platform-tips">当前年卡可在以下城市售卖</View> : <View className="platform-tips">以下城市已覆盖集群车宝门店</View>
										}
								</View>
								<View className='nav-letter'>
									<View className='nav-letter--wrap'>
										{
											city && city.list && city.list.length > 0 ? city.list.map(items=>{
												return <View className='nav-letter--name' onClick={()=>this.handleLetter(items.firstLetter)}>{items.firstLetter}</View>
											}) : null
										}
									</View>
								</View>
								{
									city && city.list && city.list.length > 0 ? city.list.map(item=>{
										return <View>
										<View className='letter' id={item.firstLetter}>{item.firstLetter}</View>
										<View>
											{item.items && item.items.length !=0 && item.items.map((area)=>{
												return <View className='area-name' onClick={()=>this.changeCity(area)}>{area.name}</View>
											})}
										</View>

										</View>
									}) : null
								}
					</ScrollView>
      </View>
      )
    }
}
export default PlatFormCity
